package Offer230;

/**
 * 二叉搜索树中第K小的元素
 *
 * @author 23737
 * @time 2021.10.17
 */
public class test {
    public static void main(String[] args) {

    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

/**
 * BFS
 */
class Solution {
    public int kthSmallest(TreeNode root, int k) {
        int leftN=findChild(root.left);
        if(leftN+1==k) return root.val;
        else if(k<=leftN){
            return kthSmallest(root.left, k);
        }
        else return kthSmallest(root.right, k-leftN-1);
    }
    /**
     *查找子节点个数
     * @param root
     * @return
     */
    public int findChild(TreeNode root){
        if(root==null) return 0;
        return findChild(root.left)+findChild(root.right)+1;
    }
}